package com.itaming.lycheeframework.support.cipher.gm;

import com.itaming.lycheeframework.support.utils.Base64Util;
import com.itaming.lycheeframework.support.utils.HexUtil;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;

import java.security.KeyPair;

/**
 * SM2密钥对
 *
 * @param publicKey  公钥
 * @param privateKey 私钥
 * @author A.Ming
 */
public record Sm2KeyPair(byte[] publicKey, byte[] privateKey) {

    /**
     * 创建SM2密钥对
     *
     * @param publicKey  BCEC公钥对象
     * @param privateKey BCEC私钥对象
     * @return SM2密钥对
     */
    public static Sm2KeyPair of(BCECPublicKey publicKey, BCECPrivateKey privateKey) {
        return new Sm2KeyPair(publicKey.getQ().getEncoded(false), privateKey.getD().toByteArray());
    }

    /**
     * 创建SM2密钥对
     *
     * @param keyPair 通用密钥对
     * @return SM2密钥对
     */
    public static Sm2KeyPair of(KeyPair keyPair) {
        if (!(keyPair.getPublic() instanceof BCECPublicKey) || !(keyPair.getPrivate() instanceof BCECPrivateKey)) {
            throw new IllegalArgumentException("KeyPair must be created by ECKeyPairGenerator");
        }
        return of(((BCECPublicKey) keyPair.getPublic()), ((BCECPrivateKey) keyPair.getPrivate()));
    }

    /**
     * 获取公钥Hex字符串
     *
     * @return 公钥Hex字符串
     */
    public String publicKeyHex() {
        return HexUtil.encodeToString(publicKey);
    }

    /**
     * 获取公钥Base64字符串
     *
     * @return 公钥Base64字符串
     */
    public String publicKeyBase64() {
        return Base64Util.encodeToString(publicKey);
    }

    /**
     * 获取公钥URL安全Base64字符串
     *
     * @return 公钥URL安全Base64字符串
     */
    public String publicKeyUrlSafeBase64() {
        return Base64Util.encodeUrlSafeToString(publicKey);
    }

    /**
     * 获取私钥Hex字符串
     *
     * @return 私钥Hex字符串
     */
    public String privateKeyHex() {
        return HexUtil.encodeToString(privateKey);
    }

    /**
     * 获取私钥Base64字符串
     *
     * @return 私钥Base64字符串
     */
    public String privateKeyBase64() {
        return Base64Util.encodeToString(privateKey);
    }

    /**
     * 获取私钥URL安全Base64字符串
     *
     * @return 私钥URL安全Base64字符串
     */
    public String privateKeyUrlSafeBase64() {
        return Base64Util.encodeUrlSafeToString(privateKey);
    }

}
